
package com.sskj.jkzx.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.sskj.jkzx.domain.entity.amap.EngMarkerInfo;
import com.sskj.utils.AmapHelp;
import com.sskj.utils.HttpHelp;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "**/sskj/amap")
@Api(value = "项目坐标信息查询", description = "项目坐标信息查询")
public class EngMarkersInfoServiceImpl {

	protected final Log logger = LogFactory.getLog(EngMarkersInfoServiceImpl.class);

	@Value("${sskj.jdServer}")
	private String jdServer;

	@Value("${sskj.amap.webServiceKey}")
	private String webServiceKey;

	@Value("${sskj.amap.city}")
	private String city;

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/markers", method = RequestMethod.GET)
	@ApiOperation(value = "监督工程坐标信息查询", httpMethod = "GET")
	public List<EngMarkerInfo> queryEngMarkerInfo() {

		List<EngMarkerInfo> result = new ArrayList<EngMarkerInfo>();

		try {
			String str = HttpHelp.sendGet(jdServer + "/seam/resource/v1/jkzx/amap/engmarkers", null);

			result = JSON.parseArray(str, EngMarkerInfo.class);
		} catch (Exception e) {
			logger.info(e.getMessage());
			result = new ArrayList<EngMarkerInfo>();
		}

		// 无法获取坐标的工程
		List<EngMarkerInfo> rm = new ArrayList<EngMarkerInfo>();

		if (result == null) {
			return new ArrayList<EngMarkerInfo>();
		}

		for (EngMarkerInfo e : result) {

			if (StringUtils.isEmpty(e.getLng()) || StringUtils.isEmpty(e.getLat())) {
				if (StringUtils.isEmpty(e.getAddr())) {
					rm.add(e);
					continue;
				} else {
					String response;
					try {
						response = AmapHelp.geo(webServiceKey, e.getAddr(), city);
					} catch (Exception ex) {
						logger.info("地址解析失败：[" + e.getAddr() + "]");
						response = null;
					}
					if (response != null) {
						String[] location = response.split(",");
						e.setLng(location[0]);
						e.setLat(location[1]);
					} else {
						rm.add(e);
						continue;
					}
				}
			} else if (StringUtils.isEmpty(e.getAddr())) {
				String address;
				try {
					address = AmapHelp.regeo(webServiceKey, e.getLng(), e.getLat());
				} catch (Exception ex) {
					logger.info("地址解析失败：[" + e.getLng() + ":" + e.getLat() + "]");
					address = null;
				}
				if (address == null) {
					rm.add(e);
					continue;
				}
				e.setAddr(address);
			}
		}

		result.removeAll(rm);

		logger.info(result.size());

		return result;
	}
}
